package com.alex.util.uuid;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NetUtil;
import com.alex.util.date.DateUtils;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import java.util.UUID;

/**
 * @author alex
 */
@Slf4j
public class UUIDUtil {
    private static long workerId = 0;

    @PostConstruct
    void init() {
        try {
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            log.info("当前机器 workerId: {}", workerId);
        } catch (Exception e) {
            log.warn("获取机器 ID 失败", e);
            workerId = NetUtil.getLocalhost().hashCode();
            log.info("当前机器 workerId: {}", workerId);
        }
    }

    public static synchronized Long snowflakeId() {
        /**
         * 构造函数
         * @param workerId 工作ID (0~31)
         * @param datacenterId 数据中心ID (0~31)
         */
        Snowflake snowflake = IdUtil.createSnowflake(workerId, 1);
        return snowflake.nextId();
    }

    /**
     * 生成不超过32位唯一ID
     *
     * @return
     */
    public static String uuid(Integer digit) {
        return UUID.randomUUID().toString().replace("-", "").substring(0, digit);
    }

    /**
     * 生成唯一ID
     *
     * @return
     */
    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 生成订单号
     *
     * @return
     */
    public static String orderId() {
        return DateUtils.dateTimeNow() + UUIDUtil.snowflakeId();
    }

    /**
     * 生成带订单类型的订单号
     *
     * @return
     */
    public static String orderId(String orderType) {
        return orderType + DateUtils.dateTimeNow() + UUIDUtil.snowflakeId();
    }

}
